﻿namespace TuneMultiCheckBox.Utils
{
  using System;
  using System.Linq;
  using Entities;
  using Microsoft.Xrm.Sdk;
  using Microsoft.Xrm.Sdk.Query;

  public static class OrganizationServiceHelper
  {
    public static IOrganizationService CreateOrganizationServiceAsSystemUser(this IOrganizationServiceFactory organizationServiceFactory, Guid currentUserId)
    {
      var service = organizationServiceFactory.CreateOrganizationService(currentUserId);

      var orgContext = new CrmContext(service);
      var systemUserId = GetSystemUserId(orgContext);

      return organizationServiceFactory.CreateOrganizationService(systemUserId);
    }

    private static Guid GetSystemUserId(this CrmContext orgContext)
    {
      var org = orgContext.OrganizationSet.FirstOrDefault();
      if (org == null)
      {
        throw new NullReferenceException("org is null");
      }

      var systemUser = org.SystemUserId;
      if (systemUser == null)
      {
        throw new NullReferenceException("systemUser is null");
      }

      return systemUser.Value;
    }
  }
}
